package com.cj.common.lang;

import java.lang.reflect.Field;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import com.cj.common.entity.Parent;
import com.cj.common.utils.ReflectionUtils;

public class SpringSideToStringBuilder extends ReflectionToStringBuilder{

	public SpringSideToStringBuilder(Object object) {
		super(object);
	}
	
    public SpringSideToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer, Class reflectUpToClass,
            boolean outputTransients, boolean outputStatics) {
        super(object, style, buffer);
        super.setUpToClass(reflectUpToClass);
        super.setAppendTransients(outputTransients);
        super.setAppendStatics(outputStatics);
    }	
    
    public static String reflectionToString(Object object) {
        return new SpringSideToStringBuilder(object, getDefaultStyle(), null, null, false, false)
        .toString();
    }

	public static ToStringStyle getDefaultStyle() {
        return SpringSideToStringStyle.getInstance();
    }
	
	@Override
    protected boolean accept(Field field) {
    	if(!super.accept(field)){
    		return false;
    	}
    	if(field.isAnnotationPresent(Parent.class)){
    		Parent parent = field.getAnnotation(Parent.class);
    		String textPropertyName;
    		if(parent.textProperty() != null)
    			textPropertyName = parent.textProperty();
    		else
    			textPropertyName = "name";
    		try {
        		Object value = field.get(this.getObject());
        		//不用.append + .append 因为会+,
        		if(value != null)
        			this.append(field.getName() + "=" + ReflectionUtils.getFieldValue(value, textPropertyName).toString());
        		else
        			this.append(field.getName() + "=null");
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			}
    		return false;
    	}
    	return true;
    }
}

